// eslint-disable-next-line @typescript-eslint/no-var-requires
const jsonServer = require("json-server");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jwt = require("jsonwebtoken");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const bodyParser = require("body-parser");
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults();

const rewrite = jsonServer.rewriter({
  "/api/*": "/$1",
});


server.use(rewrite);
server.use(middlewares);
server.use(bodyParser.json());
function createToken(payload) {
  return jwt.sign(payload, "123456", { expiresIn: "1h" });
}

function verifyToken(token) {
  return jwt.verify(token, "123456");
}
server.use("/echo", (req, res, next) => {
  console.log('token verify');
  const errorResp = {
    errno: 12001,
    message: "登录校验失败",
  };
  const authHeader = req.headers.authorization;
  if (authHeader === undefined) {
    res.jsonp(errorResp);
    return;
  }
  try {
    verifyToken(authHeader.split(" ")[1]);
    next();
  } catch (err) {
    console.log(err);
    res.jsonp(errorResp);
  }
});

server.get("/echo", (req, res) => {
  res.jsonp({
    test: "123",
  });
});

server.post("/users/genVeriCode", (req, res) => {
  res.jsonp({
    data: {
      code: "1234"
    },
  });
});


server.post("/users/loginByPhoneNumber", (req, res) => {
  console.log(req.body);
  const { phoneNumber, veriCode } = req.body;
  const accessToken = createToken({
    phoneNumber,
    veriCode,
  });
  if(veriCode === '1234'){
    res.status(200).jsonp({
      errno: 12001,
      message: "服务端登录校验失败",
    });
    return;
  }

  res.status(200).jsonp({
    data: {
      token:accessToken
    }
  });
});

server.get("/users/getUserInfo", (req, res) => {
  res.status(200).jsonp({
    data: {
      username: "张三",
      id: "user_123456",
      phoneNumber: "13800138000",
      nickName: "小张",
      description: "这是一个测试用户",
      updateAt: 1705746600000, // 2024-01-20 10:30:00 的时间戳
      createAt: 1704096000000, // 2024-01-01 08:00:00 的时间戳
      iat: Math.floor(Date.now() / 1000),
      exp: Math.floor(Date.now() / 1000) + 3600,
      picture: "https://example.com/avatar.jpg",
      gender: 1  // 1代表男性，2代表女性
    }
  });
});

router.render = (req, res) => {
  // res.jsonp({
  //   errno: 0,
  //   data: {
  //     list: res.locals.data,
  //     count: res.locals.data.length,
  //   },
  // });
  console.log(req.path.split('/').pop());
  if (req.method === 'GET' && req.path && !/\d+$/.test(req.path.split('/').pop())) {
    res.jsonp({
      errno:0,
      data:{
        list: res.locals.data,
        count: 24
      }
     })
  } else {
    res.jsonp({
      errno: 0,
      data: res.locals.data,
     })
  }
};
server.use(router);

server.listen(7001, () => {
  console.log("JSON Server is running");
});
